package br.univap.aed.cenario3.sort;

public class MergeSort {

	private Integer[] vetorSort;
	private int copias;
	private int comparacoes;
	
	public MergeSort() {
		this.copias = 0;
		this.comparacoes = 0;
	}

    private void merge(Integer[] a, Integer[] aux, int lo, int mid, int hi) {
       int i = lo, j = mid;
       for (int k = lo; k < hi; k++) {
          if(i == mid)
          {
        	  aux[k] = a[j++];
        	  comparacoes++;
          }
          else if (j == hi)
          {
        	  aux[k] = a[i++];
        	  comparacoes++;
          }
          else if (a[j] < a[i])
          {
        	  aux[k] = a[j++];
        	  comparacoes++;
          }
          else
          {
        	  aux[k] = a[i++];
        	  comparacoes++;
          }
       }

       for (int k = lo; k < hi; k++)
          a[k] = aux[k];
    }

    public void sort(Integer[] a, Integer[] aux, int lo, int hi) {

       if (hi - lo <= 1) return;

       int mid = lo + (hi - lo) / 2;
       sort(a, aux, lo, mid);
       copias++;
       sort(a, aux, mid, hi);
       copias++;

       merge(a, aux, lo, mid, hi);
    }

    public void sort(Integer[] a) {
        Integer N = a.length;
        Integer[] aux = new Integer[N];
        sort(a, aux, 0, N);
        vetorSort = a;
    }

    public Integer[] getVetorSort()
	{
		return vetorSort;
	}

	public void cleanVetorSort()
	{
		this.vetorSort = new Integer[0];
	}

	public int getCopias() {
		return copias;
	}

	public int getComparacoes() {
		return comparacoes;
	}
}

